package com.step.ems.pages.common

import android.content.Context
import android.net.Uri
import android.webkit.MimeTypeMap
import androidx.compose.runtime.mutableStateListOf
import androidx.lifecycle.ViewModel
import com.step.ems.api.ApiService
import com.step.ems.api.res.Files
import com.step.ems.common.UiState
import com.step.ems.common.launch
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import id.zelory.compressor.Compressor
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import javax.inject.Inject

@HiltViewModel
open class UploadViewModel @Inject constructor(
    @ApplicationContext val context: Context,
    open val apiService: ApiService,
) : ViewModel() {
    private val _uiState = MutableStateFlow<UiState>(UiState.Empty)
    val uploadUiState = _uiState.asStateFlow()

    val imageList: MutableList<String> = mutableStateListOf()

    fun setImages(files: List<Files>) {
        imageList.clear()
        if (files.isNotEmpty()) {
            files.forEach { item ->
                imageList.add(item.filePath)
            }
        }
    }

    fun uploadImage(imageUri: Uri) {
        launch(
            state = _uiState,
            onStart = { _uiState.value = UiState.Loading() }
        ) {
            val file: File = getFileFromUri(imageUri)
            val compressedFile = Compressor.compress(context, file)
            val body = compressedFile.asRequestBody("image/*".toMediaTypeOrNull())
            val filePart = MultipartBody.Part.createFormData("file", compressedFile.name, body)
            val url = apiService.uploadImage(filePart).get()
            imageList.add(url)
            _uiState.value = UiState.Success
        }
    }

    private suspend fun getFileFromUri(uri: Uri) = withContext(Dispatchers.IO) {
        val fileType: String? = context.contentResolver.getType(uri)
        val fileExtension = MimeTypeMap.getSingleton().getExtensionFromMimeType(fileType)
        val inputStream = context.contentResolver.openInputStream(uri)
        val tempFile = File(context.cacheDir, "photo.$fileExtension")
        tempFile.outputStream().use { fileOut ->
            inputStream?.copyTo(fileOut)
        }
        inputStream?.close()
        tempFile
    }
}